package com.dynamictpm.core;

import com.dynamictpm.build.ThreadFactoryBuilder;
import com.dynamictpm.toolkit.thread.QueueTypeEnum;
import com.dynamictpm.toolkit.thread.ThreadPoolBuilder;
import com.dynamictpm.toolkit.wrap.DynamicThreadPoolWrap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述：： 监听适配
 * <p>
 * ------------------------------------
 *
 * @program: dynamic-tpm
 * @ClassName ThreadPoolConfigAdapter
 * @author: it-yml
 * @create: 2023-07-05 09:51
 * @Version 1.0
 * --------------------------------------
 **/
public class ThreadPoolConfigAdapter{

    @Autowired
    private ThreadPoolOperation threadPoolOperation;

    private ExecutorService executorService = ThreadPoolBuilder.builder()
            .poolThreadSize(2, 4)
            .keepAliveTime(0L, TimeUnit.MILLISECONDS)
            .workQueue(QueueTypeEnum.ARRAY_BLOCKING_QUEUE, 1)
            .threadFactory("threadPool-config")
            .rejected(new ThreadPoolExecutor.DiscardOldestPolicy())
            .build();

    @Order(1025)
    @PostConstruct
    public void subscribeConfig() {
        Map<String, DynamicThreadPoolWrap> executorMap =
                ApplicationContextHolder.getBeansOfType(DynamicThreadPoolWrap.class);

        List<String> tpIdList = new ArrayList();
        executorMap.forEach((key, val) -> tpIdList.add(val.getTpId()));

        tpIdList.forEach(each -> threadPoolOperation.subscribeConfig(each, executorService, config -> callbackConfig(config)));
    }
    /**
     * 回调修改线程池配置
     *
     * @param config
     */
    public void callbackConfig(String config) {
        ThreadPoolDynamicRefresh.refreshDynamicPool(config);
    }
}
